package servlet.ann.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;

@WebServlet(urlPatterns = "/ajaxs")
@MultipartConfig
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ParamServlet-doGet");
        Map<String, String[]> parameterMap = req.getParameterMap();
        PrintWriter writer = resp.getWriter();
        parameterMap.forEach((k, v) -> {
            System.out.println(k + ":" + v[0]);
            writer.println(k + ":" + v[0]);
        });
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("ParamServlet-doPost");

        Map<String, String[]> parameterMap = req.getParameterMap();
        PrintWriter writer = resp.getWriter();
        parameterMap.forEach((k, v) -> {
            System.out.println(k + ":" + v[0]);
            writer.println(k + ":" + v[0]);
        });
        System.out.println("===========================================");
        System.out.println(readAsChars2(req));
        writer.close();
        System.out.println("===========================================");
        // 文件上传
        Collection<Part> parts = req.getParts();
        parts.parallelStream().forEach((x) -> {
            System.out.println(x.getName());
        });
        Part myfile = req.getPart("myfile");
        // myfile.write("D:/123.txt");
        System.out.println(myfile.getHeader("Content-Disposition"));
    }

    /**
     * HttpServletRequest 请求中的 body 内容仅能调用 request.getInputStream()、request.getReader() 和 request.getParameter("key") 方法读取一次
     * 重复读取会报 java.io.IOException: Stream closed 异常
     */

    // 方法一、字符串读取
    public static String readAsChars(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = request.getReader()) {
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    // 方法二、字符串读取
    public static String readAsChars2(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (InputStream is = request.getInputStream()) {
            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    // 二进制读取
    public static byte[] readAsBytes(HttpServletRequest request) {
        int len = request.getContentLength();
        byte[] buffer = new byte[len];
        try (ServletInputStream in = request.getInputStream()) {
            in.read(buffer, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}